package cn.tellsea.mq.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ 延迟队列 配置类
 *
 * @author Tellsea
 * @date 2023/9/5
 */
@Configuration
public class RabbitMqDelayConfig {

    public static final String DELAY_EXCHANGE = "spring.delay.exchange";
    public static final String DELAY_QUEUE = "spring.delay.queue";
    public static final String DELAY_ROUTING_KEY = "spring.delay.routing.key";

    @Bean(name = "delayExchange")
    public CustomExchange delayExchange() {
        Map<String, Object> map = new HashMap<>(1);
        map.put("x-delayed-type", "direct");
        return new CustomExchange(DELAY_EXCHANGE, "x-delayed-message", true, false, map);
    }

    @Bean("delayQueue")
    public Queue delayQueue() {
        return QueueBuilder.durable(DELAY_QUEUE).build();
    }

    @Bean
    public Binding ttlMsgQueueBinding(@Qualifier("delayQueue") Queue delayQueue,
                                      @Qualifier("delayExchange") CustomExchange delayExchange) {
        return BindingBuilder.bind(delayQueue).to(delayExchange).with(DELAY_ROUTING_KEY).noargs();
    }
}
